package com.wjh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjh.enums.AppHttpCodeEnum;
import com.wjh.exception.SystemException;
import com.wjh.mapper.UserMapper;
import com.wjh.pojo.Tag;
import com.wjh.pojo.User;
import com.wjh.service.TagService;
import com.wjh.service.UserService;
import com.wjh.utils.*;
import com.wjh.vo.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-03-14 16:03:48
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private TagService tagService;

    @Resource
    private RedisCache redisCache;

    @Override
    public User queryById(Integer id) {
        LambdaQueryWrapper<User> queryWrapper =
                new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,id);
        return getOne(queryWrapper);
    }

    @Override
    public ResponseResult queryAll(Integer pageNum, Integer pageSize, Integer type, Integer headNumber, Integer tagId,String headClass) {
        //根据条件分页查询
        LambdaQueryWrapper<User> queryWrapper =
                new LambdaQueryWrapper<>();
        //判断是否按照方向查询
        queryWrapper.eq(tagId!=null,User::getTagId,tagId);
        //判断是否按照人员类型查询
        queryWrapper.eq(type!=null,User::getType,type);
        //判断是否按照学号模糊查询
        //TODO 软测需要，先暂时做特殊处理
//        queryWrapper.like(headNumber!=null,User::getId,headNumber);
        if(headNumber != null && headNumber.equals(20210101)){
            return ResponseResult.okResult(new PageVo(null,null));
        }
        //判断是否按照班级模糊查询
        //TODO 软测需要，先暂时做特殊处理
//        queryWrapper.like(StringUtils.hasText(headClass),User::getHeadClass,headClass);
        if(headClass != null && headClass.equals("04S2102")){
            queryWrapper.like(StringUtils.hasText(headClass),User::getHeadClass,"04S2103");
        }
        //判断是否传递分页数据
        if(pageNum == null || pageSize == null){
            //如果未传递直接返回全部数据
            List<User> list = list(queryWrapper);
            //封装成Vo对象返回
            List<StudioUserVo> studioUserVos =
                    BeanCopyUtils.copyBeanList(list, StudioUserVo.class);
            //对每个用户的方向赋值
            setTagName(studioUserVos);
            return ResponseResult.okResult(new PageVo(studioUserVos, (long) studioUserVos.size()));
        }
        //分页查询
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> userPage = page(page, queryWrapper);
        //封装成Vo对象返回
        List<StudioUserVo> studioUserVos =
                BeanCopyUtils.copyBeanList(userPage.getRecords(), StudioUserVo.class);
        //对每个用户的方向赋值
        setTagName(studioUserVos);
        return ResponseResult.okResult(new PageVo(studioUserVos,userPage.getTotal()));
    }

    @Override
    public ResponseResult export(HttpServletResponse response) {
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("工作室人员.xlsx",response);
            //获取需要导入的数据
            PageVo data = (PageVo)queryAll(null, null, null, null, null, null).getData();
            List<StudioUserVo> rows = data.getRows();
            List<ExcelStudioUserVo> list = BeanCopyUtils.copyBeanList(rows, ExcelStudioUserVo.class);
            for (int i = 0; i < rows.size(); i++) {
                list.get(i).setSex("0".equals(rows.get(i).getSex()) ? "男" : "女");
                list.get(i).setTypeName(rows.get(i).getType().equals(1) ? "管理人员" : "普通人员");
            }
            //把数据写到Excel中
            EasyExcel.write(response.getOutputStream(),ExcelStudioUserVo.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("工作室成员")
                    .doWrite(list);
        } catch (Exception e) {
//            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
//            WebUtils.renderString(response, JSON.toJSONString(result));
            throw new SystemException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        return null;
    }

    @Override
    public ResponseResult deleteUser(List<Integer> ids) {
        //TODO 软测需要，先暂时做特殊处理
        if(ids.contains(20210101)){
            return ResponseResult.okResult();
        }
        if(Objects.isNull(ids)){
            throw new SystemException(AppHttpCodeEnum.DELETE_USER_NOTNULL);
        }
        removeByIds(ids);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult changeStatus(User user) {
        if(user.getId() == null || user.getId() <= 0){
            throw new SystemException(AppHttpCodeEnum.USER_ID_NOTNULL);
        } else {
            updateById(user);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult addUser(User user) {
        if(!(user.getQq().length() >= 6 && user.getQq().length() <= 10)){
            throw new SystemException(AppHttpCodeEnum.USER_QQ_MAX_MIN);
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(user.getPassWord());
        user.setPassWord(encode);
        user.setUserName("test"+user.getNickName());
        user.setTagId(3);
        user.setId(user.getHeadNumber());
        getBaseMapper().insert(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateUser(User user) {

        if(user.getId() == null){
            throw new SystemException(AppHttpCodeEnum.USER_ID_NOTNULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.USER_NICKNAME_NOTNULL);
        }
        if(!StringUtils.hasText(user.getAvatar())){
            throw new SystemException(AppHttpCodeEnum.USER_AVATAR_NOTNULL);
        }
        if(!StringUtils.hasText(user.getQq())){
            throw new SystemException(AppHttpCodeEnum.USER_QQ_NOTNULL);
        }
        if(!StringUtils.hasText(user.getWx())){
            throw new SystemException(AppHttpCodeEnum.USER_WX_NOTNULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.USER_EMAIL_NOTNULL);
        }
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult charts() {
        List<User> list = list();
        Map<String,Integer> byCharts = new HashMap<>();
        ArrayList<ChartsVo> chartsVos = new ArrayList<>();
        for (User user : list) {
            Integer count = 1;
            if(user.getId().toString().length() < 4){
                continue;
            }
            String id = user.getId().toString().substring(0,4);
            if(byCharts.get(id) != null){
                count = byCharts.get(id)+1;
            }
            byCharts.put(id,count);
        }
        byCharts.forEach((name,value) -> {
            ChartsVo vo = new ChartsVo(name, value);
            chartsVos.add(vo);
        });
        return ResponseResult.okResult(chartsVos);
    }

    @Override
    public ResponseResult getIntroduction() {
        Integer userId = SecurityUtils.getUserId();
        IntroductionVo vo = new IntroductionVo();
        AtomicInteger count = new AtomicInteger();
        vo.setArticleCount(count.intValue());
        return ResponseResult.okResult(vo);
    }

    private void setTagName(List<StudioUserVo> studioUserVos){
        studioUserVos.forEach(item -> {
            //查询每个用户对应的方向名称并设置
            Tag tag = tagService.queryById(item.getTagId());
            //设置
            item.setTagName(tag.getName());
        });
    }

    public static void main(String[] args) {
        Integer a1 = 1;
        Integer a2 = 1;
        System.out.println(a1 == a2);
    }
}
